package singsong;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.TargetDataLine;

public class SoundRecorder {
	private static final AudioFileFormat.Type TARGET_TYPE = AudioFileFormat.Type.WAVE;
	
	public SoundRecorder(TargetDataLine line, File outputFile) {
		this.line = line;
		this.outputFile = outputFile;
		createAudioInputStreamThread();
	}

	private void createAudioInputStreamThread() {
		audioInputStream = new AudioInputStream(line);
		thread = new Thread() {
			public void run() {
				System.out.println("Starting writing to " + outputFile.getName());
				try {
					AudioSystem.write(audioInputStream, TARGET_TYPE, outputFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("Finished writing to " + outputFile.getName());
			}
		};
	}

	public void start() {
		line.start();
		thread.start();
	}

	public void stop() {
		line.stop();
		line.flush();
		try {
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		try {
			audioInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private TargetDataLine line;
	private File outputFile;
	private AudioInputStream audioInputStream = null;
	private Thread thread = null;
}
